package org.totoro.servlet.methodpath.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author TOTORO
 * @date 2021/4/25 21:20
 * Servlet-Path过滤器：获取访问的路径，从访问路径上截取项目名，通过org.apache.commons.lang.StringUtils判断该路径是否存在网页元素路径(只能是Servlet)，获取servlet注解名和访问方法注解名，继而跳转
 */
public class MpServletFilter implements Filter {
    private static final String REGEX = "\\w+\\.\\w+";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String contextPath = request.getServletContext().getContextPath();
        String uri = request.getRequestURI();
        uri = uri.replaceAll(contextPath, "");
        if (uri.contains(".") || uri.split("/").length<1) {
            filterChain.doFilter(request, response);
            return;
        }

        if(uri.split("/").length>3){
            throw new RuntimeException("请求的路径不规范！");
        }
        String[] uris = uri.substring(1,uri.length()).split("/");
        String servletPath = uris[0];

        // 如果长度大于1，代表有注解方法，否则只有类
        if(uris.length>1) {
            String methodPath = uris[1];
            request.setAttribute("method", "/" + methodPath);
        }
        servletRequest.getRequestDispatcher("/" + servletPath).forward(request, response);
    }

    @Override
    public void destroy() {

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
}